import axios from 'axios'
import { baseUrl } from '@/config'

class HttpRequest {
  constructor (baseURL = baseUrl) {
    this.baseURL = baseURL
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseURL,
      header: {
        //
      }
    }
    return config
  }
  // 拦截器
  interceptors (instance, url) {
    // 请求拦截器
    instance.interceptors.request.use(config => {
      // 添加全局的loading
      if (!Object.keys(this.queue).length) {
        // 显示全局loading效果
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })

    // 响应拦截器
    instance.interceptors.response.use(res => {
      delete this.queue[url]
      return res
    }, error => {
      delete this.queue[url]
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    // Object.assign将默认配置与传入属性合并,相同配置会前面的为准,覆盖默认配置
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
